/* JS */

var skipChangePrice = false;
	
$().ready(function() {


	$(".featured-overlay").hide();
	$(".featured-prices .product").hover(function (){
		$(this).find(".featured-overlay").show();
	},function(){
		$(this).find(".featured-overlay").hide();
	});
	
	$("input[placeholder], textarea[placeholder]").each(function(){
		if($(this).attr("placeholder").length && $(this).val().length<=0){
			$(this).val($(this).attr("placeholder"));

			$(this).focus(function(e){
				if($(this).val() == $(this).attr("placeholder")){
					$(this).val("");
				}
			}).blur(function(e){
		    	if($(this).val().length<=0){
			      $(this).val($(this).attr("placeholder"));
			    }
			})
		}
	});
	
	$('#s1').codaSlider({
		autoHeight: false,
		autoSlide: false,
		autoSlideInterval: 1000,
		autoSlideStopWhenClicked: true,
		crossLinking: false,
		dynamicArrows: true,
		dynamicTabsPosition: "bottom"
	});
	
	$('.ms').codaSlider({
		autoHeight: false,
		autoSlide: false,
		autoSlideInterval: 1000,
		autoSlideStopWhenClicked: true,
		crossLinking: false,
		dynamicArrows: true,
		dynamicTabsPosition: "bottom"
	});
	
	$(".close").click(function() {
        $("[data-number='" + $(this).attr('data-popup-number') + "']"  ).hide();
	});
	
	$(".show-product-popup").click(function() {
        location.hash = 'product-' + $(this).attr('data-popup-number');
        $("[data-number='" + $(this).attr('data-popup-number') + "']"  ).show();
        $(document).scrollTop( $("#wrapper").offset().top );
	});
	
	$("#product-popup").hide();
	
	$("#content .tables tr td:first-child").addClass("open");
	$("#content .tables tr td:last-child").addClass("close");


    $('.submit-button').click(function() {
        $('#' + $(this).attr('data-form-id')).submit();
    });

    $('.product-count').on('blur', function() {
        skipChangePrice = true;
        var productCountObject = $(this).parent().find('.product-count'),
            countValue = parseInt(productCountObject.val());

        $(this).parent().find('.product-count').val((countValue));
        recalculatePrice(this);
        recalculateTotalPrice();

        return false;
    });


    $('.product-count').on('change', function() {
        skipChangePrice = true;
        var productCountObject = $(this).parent().find('.product-count'),
            countValue = parseInt(productCountObject.val());

        $(this).parent().find('.product-count').val((countValue));
        recalculatePrice(this);
        recalculateTotalPrice();

        return false;
    });

    $('.items-minus').click(function(){
        if (!skipChangePrice){
            var productCountObject = $(this).parent().find('.product-count'),
                countValue = parseInt(productCountObject.val()),
                changedNumber = countValue > 0 ? countValue-1 : countValue;

            $(this).parent().find('.product-count').val((changedNumber));
            recalculatePrice(this);
            recalculateTotalPrice();
        }
        skipChangePrice = false;
        return false;
    });


    $('.items-plus').click(function(){
        var productCountObject = $(this).parent().find('.product-count'),
            countValue = parseInt(productCountObject.val()),
            changedNumber = countValue + 1

        $(this).parent().find('.product-count').val((changedNumber));
        recalculatePrice(this);
        recalculateTotalPrice();
        return false;
    });

    $('.sale-radio-button').on('click', function() {
        $(this).parents('.info').find('.count-product').val($(this).val());
        $(this).parents('.info').find('.total-price').html( $(this).attr('data-price') + ' <small>P</small>');
        Cufon.replace($(this).parents('.info').find('.total-price'));
    });

    $('.count-product-mini').on('change', function() {
        var price = $(this).find('option:selected').attr('data-price');
        $(this).parents('table').find('.total-price .cufon').html( 'Цена ' + price + ' Руб.');
        Cufon.replace($(this).parents('table').find('.total-price .cufon'));
    });


    $('.count-product').on('change', function() {
        if ($(this).val() == 1) {
            $(this).parents('.info').find('.sale-radio-button').each(function() { $(this).attr('checked', false); })
        } else {
            $(this).parents('.info').find("input:radio[value='" + $(this).val() + "']").attr('checked', 'checked');
        }
        $(this).parents('.info').find('.total-price').html( $(this).find('option:selected').attr('data-price') + ' <small>P</small>');
        Cufon.replace($(this).parents('.info').find('.total-price'));
    });

    $(".show-personal-info-popup").click(function() {
        $("#product-popup").show();
        $(document).scrollTop( $("#wrapper").offset().top );
    });

    $(".close").click(function() {
        $("#product-popup").hide();
    });

    $('.purchase').on('click', function(event) {
        event.preventDefault();
        $(this).parents('form').submit();
        return true;
    });

    /**
     * Convert value to number
     *
     * @param value
     * @return {*}
     */
    function convertValueToNumber(value) {
        var number;
        switch(value)
        {
            case 5:
                number = 1;
                break;
            case 15:
                number = 2;
                break;
            case 30:
                number = 3;
                break;
            default:
                number = 0;
        }
        return number;
    }

    /**
     * convert number to value
     *
     * @param number
     * @return {*}
     */
    function convertNumberToValue(number)
    {
        var value;
        switch(number)
        {
            case 1:
                value = 5;
                break;
            case 2:
                value = 15;
                break;
            case 3:
                value = 30;
                break;
            default:
                value = 1;
        }
        return value;
    }

    /**
     * Recalculate total price
     */
    function recalculateTotalPrice()
    {
        var totalPrice=0;
        $('.product-count-block').each(function() {
            var count = parseInt($(this).find('.product-count').val()),
                price = parseInt($(this).find('.product-price').val());

            discount = $.parseJSON($(this).find('.product-discounts').val());

            maxDiscount = getMaximumDiscountPrice(price, count, discount);

            totalPrice = totalPrice + (count * (maxDiscount ? maxDiscount : price));
        });

        $('#total-price').html(totalPrice + ' <small>P</small>');
        Cufon.replace('#total-price');
    }

    function getMaximumDiscountPrice(price, count, discount)
    {
        var discountQuantity = 0, maxDiscount = 0;
        $.each(discount, function(key, value) {
            if (count >= value.quantity && discountQuantity < value.quantity) {
                discountQuantity = value.quantity;
                if (value.type == 1) {
                    maxDiscount = price - value.value;
                } else {
                    maxDiscount = price - (price / 100 * value.value);
                }
            }
        });
        return maxDiscount;
    }


    /**
     * Recalculate price
     * @param obj
     */
    function recalculatePrice(obj)
    {
        var count = parseInt($(obj).parent().find('.product-count').val()),
            price = parseInt($(obj).parent().find('.product-price').val());

            discount = $.parseJSON($(obj).parent().find('.product-discounts').val());

            maxDiscount = getMaximumDiscountPrice(price, count, discount);

        $(obj).parents('.cart-row').find('.total-item-price').html(count * (maxDiscount ? maxDiscount : price) + ' <small>P</small>');

        Cufon.replace('.total-item-price');
    }

    $('.thumb').on('click', function() {
        var image = $(this).find('img');

        $(this).parents('.gallery').find('.current').removeClass('current');
        image.next().addClass('current');

        $(this).parents('.gallery').find('.main-image-picture').attr('src', image.attr('data-img-url'));
    });

    var hashString = location.hash;
    if (hashString.match(/#product-\d+$/)){
        var productId = hashString.replace('#product-','');
        $("[data-number='" + productId + "']"  ).show();
        $(document).scrollTop( $("#wrapper").offset().top );
    }
});